<?php

/**
 * @package Core
 * @author superx
 */
abstract class Core_Application {

    /**
     *
     * @var Core_Request
     */
    public $request;
    public $params;

    public function __construct($request) {
        $this->request = $request;
        $this->params = $this->getParams();
    }

    //put your code here
    abstract function run();

    public function paramRules() {
        return array();
    }

    public function defaultParams() {
        return array();
    }

    public function getParams() {
        $ret = array();

        $rule_arr = array_merge($this->paramRules(), $this->defaultParams());

        foreach ($rule_arr as $key => $rules) {
            $default = isset($rules['default']) ? $rules['default'] : null;
            $val = $this->request->getParam($key, $default);

            $Validator = new Core_Validator();
            $Filter = new Core_Filter();

            if (!empty($rules['filters'])) {
                $Filter->setData($val);
                $Filter->setFilters($rules['filters']);
                $val = $Filter->execute();
            }

            if (!empty($rules['validators'])) {
                $Validator->addValidators($rules['validators']);
            }
            if (!$Validator->isValid($val)) {
                throw new Core_CatchableException("Invalid Param [{$key}:{$val}]", -1);
            }

            $ret[$key] = $val;
        }

        return $ret;
    }

}
